<?php
require_once 'class.phpmailer.php';
require_once 'class.smtp.php'; 
require_once 'sendEmail.php';
require_once 'emailFormat.php';

//$break_point=1;
$stop_run_time=time()+4*60+30;

$baseDir=$_SERVER["argv"][1];
$sendingDir=$baseDir."sending/";
$datefilename=date('Ymd');
$sendtDir=$baseDir."sent/".$datefilename."/";
$dirObject=dir($sendingDir);

while(false !==($fileName=$dirObject->read()))
{	
    $sendingFileName=$sendingDir.$fileName;
    if(is_file($sendingFileName)){
        $fileModifyTime=filemtime($sendingFileName);
        $fileModifyTime=$fileModifyTime+10;

        if($fileModifyTime>time()){
            continue;
        }
        echo "sending file name :".$sendingFileName."\n";

        $sendingObject=new sendEmail($sendingFileName);
        $sendflages=$sendingObject->toSend();
        
        if(!in_array(false,$sendflages)){
            if(!is_dir($sendtDir))
            {
                mkdir_p($sendtDir);
                chmod($sendtDir,0777);
            }
            $copy=copy($sendingFileName,$sendtDir.$fileName);

            if($copy){
                unlink($sendingFileName);
                echo "邮件已发送!\n";
                
                if (is_dir($sendingFileName . "_attaches")){
	            	$attachDir = $sendingFileName . "_attaches";
        	    	$attachDirMoveTo = $sendtDir.$fileName . "_attaches";
                	mkdir_p($attachDirMoveTo);
	                chmod($attachDirMoveTo,0777);
        	        $files = scandir($attachDir);
                	foreach ($files as $file){
                		if ($file == "." || $file == "..") continue;
                		rename($attachDir . "/" . $file, $attachDirMoveTo . "/" . $file);
	                }
        	        rmdir($attachDir); 
	            }
            }
        }else{
            continue;
        }
    }
    
    $currenty_time=time();
    if($stop_run_time<=$currenty_time)
    {
        break;
    }
}
function mkdir_p($dirname){
	if (!file_exists($dirname)){
		mkdir_p(dirname($dirname));
		mkdir($dirname);
	}
}

?>
